/**
 * Axios文档:https://www.axios-http.cn/docs/api_intro
 */

import axios from "axios"
import { message } from 'antd'
import { history } from '@/utils/history'
import { getToken, clearToken } from '@/utils/token'

const instance = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0'
})

// 请求拦截
instance.interceptors.request.use(config => {
  const token = getToken()
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})

//响应拦截
instance.interceptors.response.use(response => {
  return response
}, error => {
  let { response } = error
  if (response) {
    //服务器有返回内容
    var errormsg = ''
    switch (response.status) {
      case 400:
        errormsg = '错误请求'
        break
      case 401:
        errormsg = '登录失效，请重新登录'
        clearToken()
        // 跳转到登录页
        history.push('/login')
        break
      case 403:
        errormsg = '决绝访问'
        break
      case 404:
        errormsg = '请求错误，未找到该资源'
        break
      case 405:
        errormsg = '请求方法未允许'
        break
      case 408:
        errormsg = '请求超时'
        break
      case 500:
        errormsg = '服务器出错'
        break
      case 501:
        errormsg = '网络未实现'
        break
      case 502:
        errormsg = '网络错误'
        break
      case 503:
        errormsg = '服务不可用'
        break
      case 504:
        errormsg = '网络超时'
        break
      case 505:
        errormsg = 'http版本不支持该请求'
        break
      default:
        errormsg = '连接错误'
    }
    message.warning(errormsg)
    return false
  } else {
    //服务器连结果都没有返回  有可能是断网或者服务器奔溃
    if (!window.navigator.online) {
      //断网处理
      message.warning('网络中断')
      return
    } else {
      message.warning('服务器奔了')
    }
  }
  return Promise.reject(error)

})

//传递相关配置实现自定义请求

/*
*Get请求
*@param {String} url [请求的url地址]
*@param {Object} params[请求携带的参数]
*/

class Request {
  request (url, method, data, timeout) {
    return new Promise((resolve, reject) => {
      if (method === 'GET') {
        instance({
          url,
          method,
          params: data,
          timeout
        }).then((response) => {
          resolve(response.data)
        }).catch((error) => {
          reject(error)
        })
      } else {
        instance({
          url,
          method,
          data,
          timeout
        }).then((response) => {
          resolve(response.data)
        }).catch((error) => {
          reject(error)
        })
      }

    })
  }
  get (url, params, timeout = 5000) {
    return this.request(url, "GET", params, timeout)
  }
  post (url, params, timeout = 5000) {
    return this.request(url, "POST", params, timeout)
  }
  delete (url, params, timeout = 5000) {
    return this.request(url, "DELETE", params, timeout)
  }
}

const request = new Request()

export default request